package com.mt.roll.core;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.mt.roll.core.utils.StringUtils;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by FanYi on 2018-08-27 16:38.
 **/
public class MyGenerator {
    /**
     * 数据库地址
     */
    static String dbUrl = "jdbc:mysql://mysql.picaiba.com:30307/wms_00a_f";
    static String userName = "root";
    static String password = "1qaz@WSX3edc$RFV";
    /**
     * 是否去掉生成实体的属性名前缀
     */
    static String[] fieldPrefix = new String[]{"t_"};

    /**
     * 代码生成器
     *
     * @param include 需要包含的表名，允许正则表达式
     */
    private static void generateByTablesWithInjectConfig(String[] include) {
        File file = new File("");
        String path = file.getAbsolutePath();
        // 全局配置
        GlobalConfig config = new GlobalConfig();
        // 开启 activeRecord 模式
        config.setActiveRecord(true)
                //生成目录
                .setOutputDir(path + "/src/main/java")
                //生成人
                .setAuthor("mt")
                // 是否覆盖文件
                .setFileOverride(true)
                // XML ResultMap
                .setBaseResultMap(true)
                // XML columList
                .setBaseColumnList(true)
                .setOpen(false)
                // 自定义文件命名，注意 %s 会自动填充表实体属性！
                .setMapperName("%sMapper")
                .setXmlName("%sMapper")
                .setServiceName("%sServiceBiz")
                .setServiceImplName("%sServiceBizImpl");

        // 数据源配置
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL)
                .setUrl(dbUrl)
                .setUsername(userName)
                .setPassword(password)
                .setDriverName("com.mysql.jdbc.Driver");
        // 策略配置
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setVersionFieldName("version")
                .setLogicDeleteFieldName("valid")
                .setCapitalMode(true)
                .setChainModel(true)
                .setEntityColumnConstant(true)
                .setEnableSqlFilter(false)
                .setNaming(NamingStrategy.underline_to_camel)
                .setEntityLombokModel(true)
                .setTablePrefix(fieldPrefix)
                .setEntityTableFieldAnnotationEnable(true)
                //修改替换成你需要的表名，多个表名传数组
                .setInclude(include);
        // 包配置
        PackageConfig packageConfig = new PackageConfig();
        packageConfig.setParent("com.mt.roll.core.dal")
                .setEntity("entity")
                .setMapper("mapper")
                .setService("service")
                .setServiceImpl("service.impl")
                .setXml("mapper");

        //模板配置
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setController(null);

        // 代码生成器
//        AutoGenerator generator = new AutoGenerator();
        MybatisPlusGenerator generator = new MybatisPlusGenerator();
        generator.setExcludeTables("t_service");
        generator.setGlobalConfig(config)
                .setDataSource(dataSourceConfig)
                .setStrategy(strategyConfig)
                .setPackageInfo(packageConfig)
                .setTemplate(templateConfig)
                .execute();
    }

    @Test
    public void generateCodeWithInjectConfigForAllTable() {
        generateByTablesWithInjectConfig(new String[]{"t_location_storage_sub"});
    }

    public static void main(String[] args) {
        generateByTablesWithInjectConfig(new String[]{"t_goods[a-zA-Z0-9_]*"});
    }


    /**
     *
     */
    public static class MybatisPlusGenerator extends AutoGenerator {

        /**
         * 需要排除的表名，允许正则表达式
         */
        private String[] excludeTables = null;

        @Override
        protected ConfigBuilder pretreatmentConfigBuilder(ConfigBuilder config) {
            super.pretreatmentConfigBuilder(config);
            if (excludeTables != null && excludeTables.length > 0) {
                List<String> excludeTableList = Arrays.stream(excludeTables).filter(StringUtils::isNotEmpty).collect(Collectors.toList());
                config.setTableInfoList(config.getTableInfoList().stream()
                        .filter(tableInfo -> {
                            boolean excludeFlag = false;
                            String tableName = tableInfo.getName();
                            for (String excludeTableName : excludeTableList) {
                                if (excludeTableName.equalsIgnoreCase(tableName) || Pattern.matches(excludeTableName, tableName)) {
                                    excludeFlag = true;
                                    break;
                                }
                            }
                            return !excludeFlag;
                        }).collect(Collectors.toList()));
            }
            return config;
        }

        public AutoGenerator setExcludeTables(String... excludeTables) {
            this.excludeTables = excludeTables;
            return this;
        }

    }
}
